package utl.mofen.handler;

// {
//	   "fileInfo":
//	    {
//	       "id":"xxxxxx",      //接收id
//	       "file":"x.bmp",     //文件名 可以带相对路径
//	       "type":"rep",       //类型       
//	       "start":true,       //第一次
//	       "end":false,        //文件结束标志
//	       "crc":00000,        //流数据的crc
//	    }
//	}

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Hashtable;

import com.google.gson.JsonObject;

import utl.mofen.jsonStreamHandler.JSonStreamHandler;
import utl.mofen.utils.CRCUtil;
import utl.mofen.utils.DateUtil;
import utl.mofen.utils.FileUtil;
import utl.mofen.utils.GsonUtil;
import utl.mofen.utils.StringUtil;

public class FileRecvHandler extends JSonStreamHandler {
	JsonObject jsonObject = null;
	
	String basePath = "E:\\cache\\";
	
	public void doAction() throws Exception {
		System.out.println("文件存放路径:" + basePath);
		jsonObject = this.jsonStream.getJSonObject();
		
		if (!jsonObject.has("fileInfo"))
		{
			jsonStream.clear();
			throw new Exception("缺少文件头信息!");
		}
		
		JsonObject fileInfo = jsonObject.get("fileInfo").getAsJsonObject();		
		if (!fileInfo.has("id"))
		{
			jsonStream.clear();
			throw new Exception("头信息缺少id!");
		}
		
		String id = fileInfo.get("id").getAsString();
		System.out.println(GsonUtil.json2String(fileInfo));
		
		if (!fileInfo.has("file"))
		{
			jsonStream.clear();
			throw new Exception("头信息缺少file(文件名)!");
		}
		String fileName = fileInfo.get("file").getAsString();
		
		
		String typeStr = "";
		if (fileInfo.has("type"))
		{
			typeStr = fileInfo.get("type").getAsString() + "\\";
		}
		
		String newFileName = basePath + typeStr + fileName;
		String tempFileName = newFileName + ".recving";
		String infoFileName = newFileName + ".recvinfo";
		
		JsonObject json = GsonUtil.jsonFromFile(infoFileName);
		if (json==null)
		{
			json = new JsonObject();
			json.addProperty("id", id);
			json.addProperty("lastTime", DateUtil.dateTime2Str(null));
			GsonUtil.json2File(json, infoFileName);
		}else
		{		
			if (json.has("id"))
			{
				if (!id.equals(json.get("id").getAsString()))
				{
					if (json.has("lastTime"))
					{	
						Date lastOperaTime = 
								DateUtil.stringToDateTime(json.get("lastTime").getAsString());						
						if (DateUtil.secondSpan(new Date(), lastOperaTime) < 20)
						{
							throw new Exception("接收文件访问冲突!请稍候再试!");
						}
						json.remove("lastTime");
					}
					json.remove("id");
					json.addProperty("id", id);
				}
			}

			json.addProperty("lastTime", DateUtil.dateTime2Str(null));
			GsonUtil.json2File(json, infoFileName);
		}
			

		
		if (fileInfo.has("start"))
		{
			FileUtil.forceMakeDirectoryOfFile(tempFileName);
			if (fileInfo.get("start").getAsBoolean())
			{
				if (FileUtil.fileExists(tempFileName))
				{
					if (!FileUtil.deleteFile(tempFileName))
					{
						throw new Exception("删除源文件失败!");
					}
				}
			}
		}
		
		byte[] fileData = jsonStream.getStream();
//      java中的crc与Delphi crc不一致		
//		if (fileInfo.has("crc"))
//		{
//			long crcValue = fileInfo.get("crc").getAsLong();
//			long calcCrc = CRCUtil.crc(fileData);
//			if (crcValue != calcCrc)
//			{				
//				System.out.println("java crc:" + calcCrc + " delphi crc:" + crcValue);
//				throw new Exception("crc校验失败!" );
//			} else
//			{
//				System.out.println("crc校验成功....");
//			}
//		}
		
		FileUtil.append(tempFileName, jsonStream.getStream());
		
		//判断是否完成
		if (fileInfo.has("end"))
		{
			if (fileInfo.get("end").getAsBoolean())
			{	
				FileUtil.moveto(tempFileName, newFileName);
				FileUtil.deleteFile(infoFileName);
			}
		}
	}
	
	public void setBasePath(String _basePath)
	{		
		if (StringUtil.stringIsNotEmpty(_basePath))
		{
			this.basePath = FileUtil.PathWithBackslash(_basePath);
		}
		
	}
	
	public String getBasePath()
	{
		return this.basePath;		
	}
}
